package com.cmict.data.infra.service.consulthistory;

import com.alibaba.fastjson.JSONObject;
import com.cmict.data.framework.mybatis.core.query.QueryWrapperX;
import com.cmict.data.framework.security.core.util.SecurityFrameworkUtils;
import com.cmict.data.framework.tenant.core.context.TenantContextHolder;
import com.cmict.data.infra.controller.admin.message.vo.UserAnnouncementQO;
import com.cmict.data.infra.dal.dataobject.consult.ConsultDO;
import com.cmict.data.infra.dal.mysql.consult.ConsultMapper;
import com.cmict.data.system.api.message.WsMessageDTO;
import com.cmict.data.system.api.user.AdminUserApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.runtime.directive.Foreach;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import com.cmict.data.infra.controller.admin.consulthistory.vo.*;
import com.cmict.data.infra.dal.dataobject.consulthistory.ConsultHistoryDO;
import com.cmict.data.framework.common.pojo.PageResult;

import com.cmict.data.infra.convert.consulthistory.ConsultHistoryConvert;
import com.cmict.data.infra.dal.mysql.consulthistory.ConsultHistoryMapper;

import static com.cmict.data.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.cmict.data.infra.enums.ErrorCodeConstants.*;

/**
 * 咨询历史管理 Service 实现类
 *
 * @author 系统管理员
 */
@Service
@Validated
@Slf4j
public class ConsultHistoryServiceImpl implements ConsultHistoryService {

    @Resource
    private ConsultHistoryMapper consultHistoryMapper;

    @Resource
    private ConsultMapper consultMapper;

    @Resource
    private AdminUserApi adminUserApi;

    @Override
    public Long createConsultHistory(ConsultHistoryCreateReqVO createReqVO) {
        // 插入
        ConsultHistoryDO consultHistory = ConsultHistoryConvert.INSTANCE.convert(createReqVO);
        consultHistoryMapper.insert(consultHistory);
        // 返回
        return consultHistory.getId();
    }

    @Override
    public ConsultHistoryDO createHistoryByRobotChat(ConsultHistoryCreateReqVO createReqVO) {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> chatMap = new HashMap<>();
        if(null != createReqVO.getHistoryId()){
            consultHistoryMapper.deleteById(createReqVO.getHistoryId());
        }
        if( createReqVO.getToType() == -1) {//刚进来提示 内容随便传值
            ConsultHistoryDO historyResultDO = new ConsultHistoryDO();
            historyResultDO.setFromUserId(createReqVO.getToTypeId());
            historyResultDO.setToTypeId(createReqVO.getFromUserId());
            historyResultDO.setToType(0);
            resultMap.put("chatAnswer","您好，请问有什么可以帮您？");
            historyResultDO.setChatContent(JSONObject.toJSONString(resultMap));
            consultHistoryMapper.insert(historyResultDO);
//            executeChatPush(historyResultDO); //执行推送
            return historyResultDO;
        }
        if( createReqVO.getToType() == 0){//机器人
            // 首次插入
            ConsultHistoryDO consultHistory = ConsultHistoryConvert.INSTANCE.convert(createReqVO);
            consultHistory.setCreateTime(createReqVO.getTime());
            chatMap.put("chatAnswer",createReqVO.getChatContent());
            consultHistory.setChatContent(JSONObject.toJSONString(chatMap));
            consultHistoryMapper.insert(consultHistory);
            List<ConsultDO> issueTitleList =null;
            String answer = null;
            // 继续插入数据
            ConsultHistoryDO historyResultDO = new ConsultHistoryDO();
            historyResultDO.setFromUserId(createReqVO.getToTypeId());
            historyResultDO.setToTypeId(createReqVO.getFromUserId());
            historyResultDO.setToType(0);
            if(createReqVO.getIssueTitleId() == null){
                //问题
                issueTitleList =  consultMapper.getIssueTitleByRobotChat(createReqVO);
                if(issueTitleList!=null && issueTitleList.size()>0){
                    resultMap.put("chatAnswer",issueTitleList.get(0).getAnswer());
                    resultMap.put("chatIssueTitleList",issueTitleList);
                    List<ConsultDO> relevanceList = getRelevance(issueTitleList);
                    resultMap.put("relevanceConsult",relevanceList);
                }else{
                    issueTitleList =  consultMapper.getIssueTitleBySimilarRobotChat(createReqVO);
                    if(issueTitleList!=null && issueTitleList.size()>0){
                        resultMap.put("chatAnswer",issueTitleList.get(0).getAnswer());
                        resultMap.put("chatIssueTitleList",issueTitleList);
                        List<ConsultDO> relevanceList = getRelevance(issueTitleList);
                        resultMap.put("relevanceConsult",relevanceList);
                    }else{
                        resultMap.put("chatAnswer","请在系统内功能查阅。");
                    }
                }
            }else{
                ConsultDO consultDO = consultMapper.selectById(createReqVO.getIssueTitleId());
                //答案
                answer = consultDO.getAnswer();
                resultMap.put("chatAnswer",answer);
                Set<Long> consultIds = consultDO.getConsultIds();
                List<ConsultDO> list = new ArrayList<>();
                if(consultIds.size() > 0){
                    for(Long id:consultIds){
                        ConsultDO relevanceeConsultDO = consultMapper.selectById(id);
                        if(null != relevanceeConsultDO){
                            list.add(relevanceeConsultDO);
                        }
                    }
                }
                resultMap.put("relevanceConsult",list);
            }
            historyResultDO.setChatContent(JSONObject.toJSONString(resultMap));
            consultHistoryMapper.insert(historyResultDO);
//            executeChatPush(consultHistory); //多点登录 执行推送  后期优化
//            executeChatPush(historyResultDO); //执行推送
            return historyResultDO;
        }
        return null;
    }

    public List<ConsultDO> getRelevance(List<ConsultDO> issueTitleList){
        List<ConsultDO> resultList = new ArrayList<>();
        for(int i = 0;i < issueTitleList.size();i++ ){
            Set<Long> consultIds = issueTitleList.get(i).getConsultIds();
            List<ConsultDO> list = new ArrayList<>();
            if(null != consultIds && consultIds.size() > 0){
                for(Long id:consultIds){
                    ConsultDO relevanceeConsultDO = consultMapper.selectById(id);
                    if(null != relevanceeConsultDO){
                        list.add(relevanceeConsultDO);
                    }
                }
            }
            resultList.addAll(list);
        }
        return resultList;
    }
    public long executeChatPush(ConsultHistoryDO historyResultDO){
        WsMessageDTO messageDO = new WsMessageDTO();
        messageDO.setNeedBroadcast(false);   // 是否广播发送
        messageDO.setOnlyOneClientInSameKey(false); // 相同 sessionKey 的客户端只推送一次操作

        // 获取待发送的 sessionKeys
        Collection<Object> sessionKeys  =  adminUserApi.getSessionKeys().getData();
        for (Object sessionKey : sessionKeys) {
            String key = sessionKey.toString();
            if(key.contains("_")){
                String userId = key.substring(key.indexOf("_")+1 , key.length() );
                if(userId.equals(SecurityFrameworkUtils.getLoginUser().getId().toString())){
                String tenantId = key.substring(0 , key.indexOf("_")  );
                log.info(tenantId + " sessionKeys, messageDo: {}", messageDO);
                    messageDO.setMessageText(JSONObject.toJSONString(historyResultDO) );
                    List<Object> list = new ArrayList<>();
                    list.add(sessionKey);
                    messageDO.setSessionKeys(list);
                    adminUserApi.distribute(messageDO);
                }
            }
        }
        return 1;
    }

    @Override
    public void updateConsultHistory(ConsultHistoryUpdateReqVO updateReqVO) {
        // 校验存在
        this.validateConsultHistoryExists(updateReqVO.getId());
        // 更新
        ConsultHistoryDO updateObj = ConsultHistoryConvert.INSTANCE.convert(updateReqVO);
        consultHistoryMapper.updateById(updateObj);
    }

    @Override
    public void deleteConsultHistory(Long id) {
        // 校验存在
        this.validateConsultHistoryExists(id);
        // 删除
        consultHistoryMapper.deleteById(id);
    }

    private void validateConsultHistoryExists(Long id) {
        if (consultHistoryMapper.selectById(id) == null) {
            throw exception(CONSULT_HISTORY_NOT_EXISTS);
        }
    }

    @Override
    public ConsultHistoryDO getConsultHistory(Long id) {
        return consultHistoryMapper.selectById(id);
    }

    @Override
    public List<ConsultHistoryDO> getConsultHistoryList(Collection<Long> ids) {
        return consultHistoryMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<ConsultHistoryDO> getConsultHistoryPage(ConsultHistoryPageReqVO pageReqVO) {
        return consultHistoryMapper.selectPage(pageReqVO);
    }

    @Override
    public List<ConsultHistoryDO> getConsultHistoryList(ConsultHistoryExportReqVO exportReqVO) {
        return consultHistoryMapper.selectList(exportReqVO);
    }

    @Override
    public List<ConsultHistoryDO> getChatHistoryList(ConsultHistoryCreateReqVO createReqVO) {
      return   consultHistoryMapper.getChatHistoryList(createReqVO);
    }

}
